package com.it.schoolhomeos.controller;

import com.it.schoolhomeos.entity.User;
import com.it.schoolhomeos.enums.Role;
import com.it.schoolhomeos.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ADMIN')")
@Tag(name = "教师管理", description = "提供教师用户的管理功能")
public class TeacherController {

    @Autowired
    private UserService userService;

    @GetMapping("/teachers/init")
    @Operation(summary = "初始化测试数据", description = "创建一个测试教师用户")
    public ResponseEntity<Map<String, Object>> initTestData() {
        try {
            // 检查是否已存在
            if (userService.existsByUsername("teacher1")) {
                return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "message", "测试教师用户已存在",
                    "username", "teacher1",
                    "password", "123456"
                ));
            }
            
            // 创建测试教师用户
            User teacher = new User();
            teacher.setUsername("teacher1");
            teacher.setPassword("123456"); // 会在service中加密
            teacher.setName("测试教师");
            teacher.setPhone("13800138002");
            teacher.setEmail("teacher1@example.com");
            teacher.setRole(Role.TEACHER);
            teacher.setEnabled(true);
            teacher.setCreateTime(LocalDateTime.now());
            teacher.setUpdateTime(LocalDateTime.now());
            
            User savedTeacher = userService.createTeacher(teacher);
            
            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "测试教师用户创建成功");
            result.put("username", savedTeacher.getUsername());
            result.put("password", "123456"); // 原始密码
            result.put("id", savedTeacher.getId());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                "status", "error",
                "message", "创建测试教师用户失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取简易教师列表，用于下拉选择
     * 
     * @return 包含教师ID和姓名的简易列表
     */
    @GetMapping("/teachers/list")
    @Operation(summary = "获取教师简易列表", description = "获取所有教师的ID和姓名，用于下拉选择")
    public ResponseEntity<Map<String, Object>> getTeacherList() {
        // 使用分页查询，但设置较大的页面大小以获取所有教师
        Page<User> teachersPage = userService.findTeachers(0, 1000, null);
        List<User> teachers = teachersPage.getContent();
        
        List<Map<String, Object>> simplifiedTeachers = teachers.stream()
                .map(teacher -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", teacher.getId());
                    map.put("name", teacher.getName());
                    return map;
                })
                .collect(Collectors.toList());
        
        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "获取教师列表成功");
        response.put("data", simplifiedTeachers);
        
        return ResponseEntity.ok(response);
    }

    @GetMapping("/teachers")
    @Operation(summary = "获取教师列表", description = "分页获取所有教师用户")
    public ResponseEntity<Page<User>> getTeachers(
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        return ResponseEntity.ok(userService.findTeachers(page, size, keyword));
    }

    @GetMapping("/teachers/{id}")
    @Operation(summary = "获取教师详情", description = "根据ID获取教师用户详情")
    public ResponseEntity<User> getTeacher(@Parameter(description = "教师ID") @PathVariable Long id) {
        return ResponseEntity.ok(userService.findTeacherById(id));
    }

    @PostMapping("/teachers")
    @Operation(summary = "创建教师", description = "创建新的教师用户")
    public ResponseEntity<User> createTeacher(@Parameter(description = "教师信息") @RequestBody User user) {
        return ResponseEntity.ok(userService.createTeacher(user));
    }

    @PutMapping("/teachers/{id}")
    @Operation(summary = "更新教师", description = "更新教师用户信息")
    public ResponseEntity<User> updateTeacher(
            @Parameter(description = "教师ID") @PathVariable Long id,
            @Parameter(description = "教师信息") @RequestBody User user) {
        // 获取原有教师信息
        User existingTeacher = userService.findTeacherById(id);
        
        // 设置ID和不可修改的字段
        user.setId(id);
        user.setUsername(existingTeacher.getUsername());
        user.setRole(Role.TEACHER);
        
        // 如果某些必填字段为空，则保留原有值
        if (user.getName() == null) {
            user.setName(existingTeacher.getName());
        }
        if (user.getPassword() == null) {
            user.setPassword(existingTeacher.getPassword());
        }
        if (user.getEnabled() == null) {
            user.setEnabled(existingTeacher.getEnabled());
        }
        
        // 设置更新时间
        user.setUpdateTime(LocalDateTime.now());
        
        return ResponseEntity.ok(userService.updateTeacher(user));
    }

    @DeleteMapping("/teachers/{id}")
    @Operation(summary = "删除教师", description = "删除指定的教师用户")
    public ResponseEntity<Void> deleteTeacher(@Parameter(description = "教师ID") @PathVariable Long id) {
        userService.deleteTeacher(id);
        return ResponseEntity.ok().build();
    }
} 